import pyaudio,wave
import requests
import json
import base64
from urllib.parse import quote
import snowboydecoder
VOICE='voice.wav'
RETVOICE='vocalization.wav'
class voice():
    def __init__(self):
        pass
    def record(self,time=5,save_file=VOICE):
        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 8000
        RECORD_SECONDS = time  #需要录制的时间
        WAVE_OUTPUT_FILENAME = save_file	#保存的文件名
        self.play_file=save_file
        p = pyaudio.PyAudio()	#初始化
        print("ON")
        snowboydecoder.play_audio_file()
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                            frames_per_buffer=CHUNK)#创建录音文件
        frames = []

        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
            data = stream.read(CHUNK)
            frames.append(data)#开始录音
        stream.stop_stream()
        stream.close()
        p.terminate()

        snowboydecoder.play_audio_file()
        print("OFF")
        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')	#保存
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

    def play(self,play_file=RETVOICE):
        CHUNK = 1024
        wf = wave.open(play_file, 'rb')
        p = pyaudio.PyAudio()
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)

        data = wf.readframes(CHUNK)

        while data != b'':
            stream.write(data)
            data = wf.readframes(CHUNK)

        stream.stop_stream()
        stream.close()
        p.terminate()

class baiduapi():
    def __init__(self):
        self.API_KEY = 'HEK51LdVDBQeihxc3PV6EdlY'
        self.SECRET_KEY = 'REDXa2j3ACAdyuvxb0wlle2wVn0PBPN9'
        self.getToken()
    def getToken(self):
        url='https://aip.baidubce.com/oauth/2.0/token'
        param={
            'grant_type':'client_credentials',
            'client_id':self.API_KEY,
            'client_secret':self.SECRET_KEY
        }
        ret=requests.post(url,data=param)
        ret=json.loads(ret.text)
        self.TOKEN=ret['access_token']
        self.TOKEN_EXPIRE=ret['expires_in']
    def distinguish(self,src=VOICE):
        with open(src, 'rb') as speech_file:
            speech_data = speech_file.read()
        length = len(speech_data)
        speech = base64.b64encode(speech_data)
        speech = str(speech, 'utf-8')
        url='http://vop.baidu.com/server_api'
        param={
            'format':'wav',
            'rate':8000,
            'channel':1,
            'cuid':'voicehelper',
            'token':self.TOKEN,
            'speech':speech,
            'len':length
        }
        param=json.dumps(param)

        ret=requests.post(url=url,data=param.encode('utf-8'),headers={'Content-Type':'application/json'})
        ret=json.loads(ret.text)
        if ret['err_msg']=='success.':
            return ret['result'][0]
        else:
            return ret['err_msg']
    def vocalization(self,src:str):
        url='http://tsn.baidu.com/text2audio'
        tex=quote(src)
        param={
            'tex':tex,
            'tok':self.TOKEN,
            'cuid':'voicehelper',
            'ctp':1,
            'lan':'zh',
            'per':0,
            'aue':6,
            'spd':5,
            'pit':5,
            'vol':15,
        }
        ret=requests.post(url,data=param)
        if ret.headers['Content-Type'].split('/')[0]=='audio':
            with open(RETVOICE,'wb') as f:
                f.write(ret.content)

class turing():
    def __init__(self):
        self.APIKEY='3d6a748751f444f69e226405ea7c9742'
    def sendMessage(self,msg:str):
        url='http://openapi.tuling123.com/openapi/api/v2'
        param={'reqType':0,
               'perception':{
                   'inputText':{
                       "text":msg
                   },
                   'selfInfo':{
                       'location':{
                           'city':'乌鲁木齐'
                       }
                   },
               },
               'userInfo':{
                       "apiKey": self.APIKEY,
                       "userId": "wuyu"
                   }}
        param=json.dumps(param)
        ret=requests.post(url,data=param)
        ret=json.loads(ret.text)
        retText=ret['results'][0]['values']['text']
        return retText

